<?php
require_once 'Xiachufang/logic/Recipe.php';
class RecipeController extends BaseController {
	function indexAction() {
		$recipeId = (int)$this->_getParam('recipeId');
		$recipeEntity = new RecipeEntity();
		if (!$recipeEntity->get($recipeId)) notFound();
		$recipe = $recipeEntity->getDataArray();
		
		$ingredients = array();
		if (preg_match_all("/([a-zA-Z\x{4e00}-\x{9fa5}()（）]+)(\d+)克\s*/u", $recipeEntity->ingredients, $matches)) {
			$len = count($matches[0]);
			for($i = 0; $i < $len; $i++) {
				$ingredients[] = array(
					"name"=>$matches[1][$i],
					"weight"=>$matches[2][$i],
				);
			}
		}
		
		// 获取对菜谱进行过的活动
		require 'Xiachufang/logic/Event.php';
		$actorId = $this->_actorId;
		$eventList = EventLogic::getActorEvents($recipeId, $actorId);
		$recipe = array_merge($recipe, $eventList);
		
		// 获取谁做过这个菜谱
		require 'Xiachufang/logic/Food.php';
		require_once 'Xiachufang/util/TimeUtil.php';
		$foodIdList = FoodLogic::getLastFoodIds(5, $recipeId);
		$foodList = array();
		foreach($foodIdList as $id) {
			$foodEntity = new FoodEntity();
			if (!$foodEntity->get($id)) break;
			$actor = new ActorEntity();
			$actorName = "未知";
			if ($actor->get($foodEntity->actorId)) {
				$actorName = $actor->nickname;
			}
			
			$foodList[] = array(
				"foodId"=>$id,
				"actorId"=>$actor->actorId,
				"actorName"=>$actor->nickname,
				"description"=>mb_strlen($foodEntity->description,"utf-8") > 54 ? mb_substr($foodEntity->description, 0, 54, "utf-8")."..." : $foodEntity->description,
				"createTime"=>TimeUtil::format($foodEntity->createTime),
				"updateTime"=>$foodEntity->updateTime,
			);
		}
		
		// 获取菜谱的评论
		require 'Xiachufang/logic/Remark.php';
		require_once 'Xiachufang/entity/Actor.php';
		$remarks= RemarkLogic::getRecipeRemarks($recipeId);
		$remarkList = array();
		foreach($remarks as $row) {
			$aid = $row["actor_id"];
			$actor = new ActorEntity();
			$actorName = "未知";
			if ($actor->get($aid)) {
				$actorName = $actor->nickname;
			}
			$remarkList[] = array(
				"remarkId"=>$row["remark_id"],
				"actorId"=>$aid,
				"actorName" => $actorName,
				"content" => $row["content"],
				"createTime" => TimeUtil::format($row["create_time"]),
			);
		}
		
		// 获取常用的标签
		require 'Xiachufang/logic/Tag.php';
		$tagList = TagLogic::getHotTags(10, $recipeId);
		
		
		// 获取谁编辑过这个菜谱
		require 'Xiachufang/logic/Wiki.php';
		$rows = WikiLogic::getRecipeActorIds($recipeId);
		$actorList = array();
		foreach($rows as $row) {
			$aid = $row["actor_id"];
			$wikiId = $row["recipe_wiki_id"];
			$actor = new ActorEntity();
			if (!$actor->get($aid)) continue;
			$actorList[] = array(
				"actorId"=>$aid,
				"nickname"=>$actor->nickname,
				"wikiId"=>$wikiId,
			);
		}		
		
		$this->smarty->assign(array(
			"pageTitle"=>$recipeEntity->name,
			"pageDescription"=>$recipeEntity->description,
		));
		
		$this->smarty->assign_by_ref("recipe", $recipe);
		$this->smarty->assign_by_ref("ingredients", $ingredients);
		$this->smarty->assign_by_ref("foodList", $foodList);
		$this->smarty->assign_by_ref("remarkList", $remarkList);
		$this->smarty->assign_by_ref("tagList", $tagList);
		$this->smarty->assign_by_ref("actorList", $actorList);
		$this->display();
	}
	
	/**
	 * 编辑菜谱
	 *
	 */
	function editAction() {
		$this->checkLogin();
		$recipeId = (int)$this->_getParam('recipeId');
		$recipeEntity = new RecipeEntity();
		if (!$recipeEntity->get($recipeId)) notFound();
		
		$recipe = $recipeEntity->getDataArray();
		$recipe["directions"] = preg_replace("/<br\s*\/?>/i","\n", $recipe["directions"]);
		$recipe["skill"] = preg_replace("/<br\s*\/?>/i","\n", $recipe["skill"]);
		$recipe["description"] = preg_replace("/<br\s*\/?>/i","\n", $recipe["description"]);
		
		$checkCode = RecipeLogic::getRecipeNameCheckCode($recipe->name);
		
		$this->smarty->assign(array(
			"pageTitle"=>"编辑菜谱“".$recipeEntity->name."”",
			"recipe"=>$recipe,
			"checkCode"=>$checkCode,
		));
		$this->display();;
	}
	
	
	/**
	 * 上传做过的菜谱
	 *
	 */
	function uploadAction() {
		$this->checkLogin();
		$recipeId = (int)$this->_getParam('recipeId');
		$recipe = new RecipeEntity();
		if (!$recipe->get($recipeId)) {
			notFound();
		}
		
		require 'Xiachufang/logic/Tag.php';
		$allTags = TagLogic::getHotTags(20, $recipeId);
		$myTags = TagLogic::getActorHotTags(20, $this->_actorId);
		$this->smarty->assign_by_ref("allTags", $allTags);
		$this->smarty->assign_by_ref("myTags", $myTags);
		
		$this->smarty->assign(array(
			"pageTitle"=>"上传做过的“".$recipe->name."”",
			"food"=>$recipe->getDataArray(array("recipeId","name")),
			"typeId"=>0,
		));
		$this->smarty->display('food/upload.tpl');
	}
	
	/**
	 * 添加菜谱
	 *
	 */
	function addAction() {
		$this->checkLogin("/recipe/add");
		$step = !isset($_POST["step"]) ? 1 : intval($_POST["step"]);
		$recipeName = trim($_POST["recipeName"]);
		if ($step == 2 && !$recipeName) notFound();
		if ($step == 2) {
			$recipes = RecipeLogic::findRecipe($recipeName);
			if ($recipes["same"]) {
				$this->smarty->assign("recipe", $recipes["same"]);
			} else {
				// 如果没有找到相同的菜谱，则直接进入第三步
				$step = 3;
				$checkCode = RecipeLogic::getRecipeNameCheckCode($recipeName);
			}
		}
		$this->smarty->assign(array(
			"pageTitle"=>"添加菜谱",
			"step"=>$step,
			"recipeName"=>$recipeName,
			"checkCode"=>$checkCode,
		));
		$this->display();
	}
	

	/**
	 * 标签
	 *
	 */
	function tagAction() {
		$actorId = (int)$this->_getParam('actorId');
		$tag = trim($this->_getParam('tag'));
		if ($actorId > 0) {
			$actor = new ActorEntity();
			if (!$actor->get($actorId)) alert("actorId=$actorId的用户不存在");
		}
		
		require 'Xiachufang/logic/Tag.php';
		$page = (int)$this->_getParam('page', 1) - 1;
		$pageSize = 20;
		$pageResult = TagLogic::pagedGetRecipeIds($tag, $this->_pi, $pageSize, $actorId);
		$recipeList = array();
		if ($pageResult->total > 0) {
			foreach($pageResult->data as $recipeId) {
				$recipe = new RecipeEntity();
				if (!$recipe->get($recipeId)) continue;
				$recipeList[] = $recipe->getDataArray(array("recipeId","name","description"));
			}
		}
		
		$this->smarty->assign(array(
				"totalNum"=>$pageResult->total,
				"tag"=>$tag,
				"actorId"=>$actorId,
		));
		if ($actorId > 0) {
			$this->smarty->assign(array(
				"pageNav"=>$pageResult->render("/people/".$actorId."/tag/".$tag."/{0}"),
				"pageTitle"=>$actor->nickname."/标签/".$tag,
				"pageDescription"=>$actor->nickname."标签[$tag]下的菜谱",
				"actorName"=>$actor->nickname,
			));
		} else {
			$this->smarty->assign(array(
				"pageNav"=>$pageResult->render("/tag/".$tag."/{0}"),
				"pageTitle"=>"标签/".$tag,
				"pageDescription"=>"标签[$tag]下的菜谱",
			));
		}
		$this->smarty->assign_by_ref("recipeList", $recipeList);
		$this->display();
	}
	
	/**
	 * 分类浏览
	 *
	 */
	function tagsAction() {
		$pageSize = 100;
		require 'lib/logic/Tag.php';
		$pageResult = TagLogic::pagedGetTags($this->_pi, $pageSize);
		$this->smarty->assign(array(
			"pageNav"=>$pageResult->render("/tags?page={0}"),
		));
		$this->smarty->assign(array(
			"pageTitle"=>"分类浏览",
			"pageDescription"=>"分类浏览",
		));
		$this->smarty->assign_by_ref("tagList", $pageResult->data);
		$this->display();
	}
	
	/**
	 * 用户编辑的菜谱
	 *
	 */
	function wikiAction() {
		require_once 'Xiachufang/entity/RecipeWiki.php';
		$wikiId = (int)$this->_getParam('wikiId');
		$wikiEntity = new RecipeWikiEntity();
		if (!$wikiEntity->get($wikiId)) notFound();
		$wiki = $wikiEntity->getDataArray();
		$recipe = new RecipeEntity();
		if (!$recipe->get($wikiEntity->recipeId)) notFound();
		$wiki["wikiId"] = $wikiId;
		$wiki["name"] = $recipe->name;
		
		$ingredients = array();
		if (preg_match_all("/([a-zA-Z\x{4e00}-\x{9fa5}()（）]+)(\d+)克\s*/u", $wikiEntity->ingredients, $matches)) {
			$len = count($matches[0]);
			for($i = 0; $i < $len; $i++) {
				$ingredients[] = array(
					"name"=>$matches[1][$i],
					"weight"=>$matches[2][$i],
				);
			}
		}
		
		$actor = new ActorEntity();
		if ($actor->get($wikiEntity->actorId)) {
			$wiki["actorName"] = $actor->nickname;
		}
		
		switch($wikiEntity->status) {
			case 0:
				$wiki["editStatus"] = "编辑尚未对该内容进行审核，请耐心等待。";
				break;
			case 1:
				$wiki["editStatus"] = "该内容没有通过编辑的审核。";
				break;
			case 2:
				$wiki["editStatus"] = "该内容已经通过编辑的审核。";
				break;
		}
		
		$isMyself = $this->_actorId == $wikiEntity->actorId;
		$this->smarty->assign(array(
			"isMyself"=>$isMyself,
			"pageTitle"=>($isMyself ? "我" : $actor->nickname)."编辑的“".$recipe->name."”",
		));
		$this->smarty->assign("recipe",array(
			"recipeId"=>$recipe->recipeId,
			"name"=>$recipe->name,
		));
		$this->smarty->assign("wiki", $wiki);
		$this->smarty->assign_by_ref("ingredients", $ingredients);
		$this->display();
	}
}
?>